package org.zero.service;

import java.io.IOException;
import java.net.Socket;
import java.util.Objects;

import org.zero.dao.ServerRunStatus;
import org.zero.dao.UserOperator;
import org.zero.entity.Request;
import org.zero.entity.Response;
import org.zero.entity.User;
import org.zero.view.ServerWindow;

public class LoginService implements ServerService {

	@Override
	public void service(Request request, Socket socket, ServerWindow serverWindow) throws IOException {
		UserOperator userOperator = new UserOperator();
		String id = request.getFromUser().getId();
		serverWindow.println("用户【" + id + "】正在尝试登录...");
		User user = userOperator.getUserById(id);

		Response response = new Response();
		response.setResponseServiceName(request.getRequestServiceName());
		// 用户不存在
		if (Objects.isNull(user)) {
			response.setResponseCode(Response.LOGIN_USERNAME_INVALID);
			response.setMessage("QQ号未注册！！！");
			serverWindow.println("用户【" + id + "】登陆失败，原因：该QQ号不存在！\n");
			send(socket, response);
			return;
		}

		// 密码错误
		if (!Objects.equals(user.getPassword(), request.getFromUser().getPassword())) {
			response.setResponseCode(Response.LOGIN_PASSWORD_ERROR);
			response.setMessage("密码错误！！！");
			serverWindow.println("用户【" + id + "】登陆失败，原因：密码错误！\n");
			send(socket, response);
			return;
		}

		// 登录成功
		response.setResponseCode(Response.LOGIN_SUCCESS);
		response.setMessage("欢迎您，" + user.getNickname() + "！");
		// 更新 IP 和 端口，并更新文件信息
		user.setIp(socket.getInetAddress().getHostAddress());
		user.setPort(socket.getPort());
		userOperator.updateUser(user);
		// 设置登录状态
		user.setOnline(true);
		response.setToUser(user);
		serverWindow.println(user.getNickname() + "-" + user.getName() + "【" + id + "】登陆成功\n");
		// 保存在线用户的 Socket
		ServerRunStatus.setSocket(user, socket);
		send(socket, response);
	}

}
